package com.happystudy.controller;

import com.happpystudy.model.LearnerInfo;
import com.happpystudy.model.User;
import com.happpystudy.service.UserService;
import com.happystudy.message.BaseMessageModel;
import com.happystudy.message.ErrorMessageType;
import com.happystudy.message.LocationMessage;
import com.happystudy.util.KeyUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author LYJ
 */
@Controller
public class LoginController {

    @Resource
    UserService userService;

    @Resource
    RedisTemplate redisTemplate;

    @GetMapping("/login")
    public String returnLoginHtml(){
        return "login";
    }

    @GetMapping("/login/doLogin")
    @ResponseBody
    public BaseMessageModel login(User record, HttpServletRequest request){
        HttpSession session = request.getSession(false);
        User user = userService.doLogin(record);
        System.out.println(user);
        BaseMessageModel message;
        if (user!=null){
            session = request.getSession();
            session.setAttribute("currentLoginUser",user);
            message = new LocationMessage(
                    "login successful!",
                    true,
                    ErrorMessageType.SUCCESS_CODE,
                    ErrorMessageType.SUCCESS_MSG,
                    "/success"
            );

        }else {
            message = new LocationMessage(
                    "login fail!",
                    false,
                    ErrorMessageType.USERNAME_OR_PASSWORD_INCORRECT_CODE,
                    ErrorMessageType.USERNAME_OR_PASSWORD_INCORRECT_MSG,""
            );
        }
        return message;
    }
}
